var express = require('express')
var winston = require('winston');
var schedule = require('node-schedule');
var moment = require('moment');
var engines = require('consolidate');
var utils = require('../AlfredWorkflowUtils.js');
var connection = require('../AlfredWorkflowMysqlServer.js');
var mysql = require('mysql');

var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

var logger = initExpressLogger();
logger.info("success components init started.");

var app = express();
// for parsing application/json
app.use(bodyParser.json()); 
// for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true })); 

initExpressGlobalConsts();
initExpressHtmlEngine();
initExpressActions();
initExpressBindingPort();
// scheduleJobs();

logger.info("success components init finished.");

function initExpressActions() {
	app.listen(9999);
	logger.info("success initExpressActions");
}
function initExpressBindingPort() {
	// mount static files.
	app.use('/open', express.static('/Users/Steve/tools/myGit/xNode/public'));

	app.get('/', function(req, res) {
		doGetAndPost(req, res);
	});

	app.get('/v1/is_mobile_valid', function(req, res) {
		var params = [req.query.mobile];
		connection.executeSql("select count(*) as result from mms_member where mobile=? ", params).then(
				function(rows) {
					res.send( rows[0].result>0);
				}).catch(function(err){
					logger.error(err);
					res.send(err);
				});
	});
	
	app.post('/alfred/workflow/listUrl', function(req, res) {
		var params = [req.query.mobile];
		
		var length = parseInt(req.body.length);
		var start = parseInt(req.body.start);
		var pagingStr = start+','+length;
		
		var querySql = "select * from alfred_workflow_urls where 1=1 limit "+pagingStr;
		var countSql = "select count(*) as result from alfred_workflow_urls where 1=1";
		var resultObject ={recordsFiltered:0,recordsTotal:0,data:''};
		
		var countChain = connection.executeSql(countSql, params).then(
				function(rows) {
					var totalLength = rows[0].result;
					resultObject.recordsFiltered = resultObject.recordsTotal = totalLength;
					return connection.executeSql(querySql, params);
				}).then(
						function(rows) {
							resultObject.data = rows;
							var result = JSON.stringify(resultObject);   
							res.send(result);
						}).catch(function(err){
							logger.error(err);
							res.send(err);
						});
	});
	
	app.all('/alfred/workflow/listAllUrl', function(req, res) {
		var querySql = "select * from alfred_workflow_urls where 1=1 order by last_check_time desc";
		var resultObject ={recordsFiltered:0,recordsTotal:0,data:''};
		
		var countChain = connection.executeSql(querySql).then(
						function(rows) {
							resultObject.recordsFiltered = resultObject.recordsTotal = rows.length;
							resultObject.data = rows;
							var result = JSON.stringify(resultObject);   
							res.send(result);
						}).catch(function(err){
							logger.error(err);
							res.send(err);
						});
	});
	
	app.post('/alfred/workflow/deleteUrl', upload.array(), function (req, res, next) {
		var params = [mysql.escape(req.body.myIds)];
		var sql = "delete from alfred_workflow_urls where id in ("+mysql.escape(req.body.myIds)+" ) ";
		connection.executeSql(sql,params).then(
				function(result) {
					logger.info("you have delete rows of:%s",result.affectedRows);
					res.send(JSON.stringify({ret:0}));
				}).catch(function(err){
					logger.error(err);
					res.send(JSON.stringify({ret:-1,msg:err}));
				});
	});
	
	app.post('/alfred/workflow/saveOrUpdateUrl', upload.array(), function (req, res, next) {
		
		var type;
		var currentDate = moment().toDate();
		if(req.body){
			if(req.body.id){
				type = "update";
			}else{
				type = "save";
			}
		}else{
			res.send(JSON.stringify(failureJson));
			return;
		}
		if(type == "save"){
			var model = {
					id: utils.generateUUID(),
					keyword: req.body.keyword,
					url: req.body.url,
					desc: req.body.desc,
					create_time:currentDate,
					last_check_time:currentDate
			};
			var sql = "insert into alfred_workflow_urls set ? ";
			var successJson = {ret:0};
			var failureJson = {ret:-1};
			connection.executeSql(sql, model).then(
					function(rows) {
						res.send(JSON.stringify(successJson));
					}).catch(function(err){
						logger.error(err);
						res.send(JSON.stringify(failureJson));
					});
			return;
		}else if(type=="update"){
			var model = {
					keyword: req.body.keyword,
					url: req.body.url,
					desc: req.body.desc,
					create_time:currentDate
			};
			var params = [req.body.keyword,req.body.url,req.body.desc,req.body.id];
			var sql = "update alfred_workflow_urls set ? where id = "+mysql.escape(req.body.id)+ " ";
			connection.executeSql(sql, model).then(
					function(rows) {
						res.send(JSON.stringify({ret:0}));
					}).catch(function(err){
						logger.error(err);
						res.send(JSON.stringify({ret:-1}));
					});
			return;
		}else{
			res.send(JSON.stringify({ret:0}));
			return;
		}
	});
	
	app.get('/v1/get_mmsMemberInfo', function(req, res) {
		var params = [req.query.mobile];
		connection.executeSql("select * from mms_member limit 1", params).then(
				function(rows) {
					res.send(rows);
				}).catch(function(err){
					logger.error(err);
					res.send(err);
				});
	});

	app.post('/', function(req, res) {
		doGetAndPost(req, res);
	});
	logger.info("success initExpressBindingPort");
}

function initExpressLogger() {
	var logger = new (winston.Logger)(
			{
				transports : [ new (winston.transports.Console)(
						{
							timestamp : function() {
								return moment().format();
							},
							formatter : function(options) {
								// Return string will be passed to logger.
								return options.timestamp()
										+ ' '
										+ options.level.toUpperCase()
										+ ' '
										+ (undefined !== options.message ? options.message
												: '')
										+ (options.meta
												&& Object.keys(options.meta).length ? '\n\t'
												+ JSON.stringify(options.meta)
												: '');
							}
						}) ]
			});
	logger.info("success init global logger.");
	return logger;
}

function doGetAndPost(req, res) {
	// res.send('receive get or post here.' + req.query);
	res.render('one/test.html', {
		token : app.locals.home
	});
}

function initExpressHtmlEngine() {
	app.engine('html', engines.mustache);
	app.set('view engine', 'html');
	app.set('views', app.locals.home + '/views');
	logger.info("success initExpressHtmlEngine");
}

function initExpressGlobalConsts() {
	app.locals.email = "nevermissing@vip.qq.com";
	app.locals.home = __dirname;
	logger.info("success initExpressGlobalConsts");
}